import { login } from '@/api/login'
import { setToken, getToken } from '@/utils/token'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    username: '',
    avatar: '',
    roles: ['admin']
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        const { account, password } = userInfo
        login({ account: account.trim(), password })
          .then(res => {
            commit('SET_TOKEN', res.data.data.token)
            commit('SET_ROLES', ['admin'])
            setToken(res.data.data.token)
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // user logout
    logout({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        commit('SET_AVATAR', '')
        // setUserInfo()
        // removeToken()
        // resetRouter()
        resolve()
      })
    }
  }
}